﻿using System;
using Alserve.Ffl;
using Alserve.Ffl.Data;
using System.IO;

public partial class ffl_anonymous_webusercontrols_newsticker : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           RefreshNewsFeed();
           GetRandomPlayerImage();
        }
    }

    private void RefreshNewsFeed()
    {
        Skip skipInstance = new Skip();
        DateTime lastNewsUpdate = DateTime.Now;
        skipInstance.Where.Keyword.Value = "News";

        if (skipInstance.Query.Load())
            lastNewsUpdate = skipInstance.SkipDate;

        if (DateTime.Now.AddMinutes(-30) > lastNewsUpdate)
        {
            EspnImport thisEspnImport = new EspnImport();
            thisEspnImport.ImportNewsFeed();
            skipInstance.SkipDate = DateTime.Now;
            skipInstance.Save();
        }

        NewsFeed thisNewsFeed = new NewsFeed();
        thisNewsFeed.LoadAll();
        NewsFeedRepeater.DataSource = thisNewsFeed.DefaultView;
        NewsFeedRepeater.DataBind();
    }

    private void GetRandomPlayerImage()
    {
        PlayerImage.ImageUrl = String.Empty;
        Skip thisSkip = new Skip();
        thisSkip.Where.Keyword.Value = "PlayerMax";
        if (thisSkip.Query.Load())
        {
            Int16 count = 0;
            while (PlayerImage.ImageUrl == String.Empty && count <= 20)
            {
                Int32 espnPlayerCount = thisSkip.SkipNumber;
                Random newRandom = new Random();

                EspnPlayer thisEspnPlayer = new EspnPlayer();
                if (thisEspnPlayer.LoadByPrimaryKey(newRandom.Next(1, espnPlayerCount)))
                {
                    if (File.Exists(Server.MapPath("~/ffl/images/players/" + thisEspnPlayer.EspnPlayerId.ToString() + ".jpg")))
                    {
                        PlayerImage.ImageUrl = "~/ffl/images/players/" + thisEspnPlayer.EspnPlayerId.ToString() + ".jpg";

                        Player thisPlayer = new Player();
                        if (thisPlayer.LoadByPrimaryKey(thisEspnPlayer.PlayerId))
                            PlayerHyperLink.Text = (thisPlayer.Forename + " " + thisPlayer.Surname).Trim();
                    }
                }
                count++;
            }
        }
    }
}
